package com.topboya.officeuser.service;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.github.wxpay.sdk.WXPayUtil;
import com.sun.media.jfxmedia.logging.Logger;
import com.topboya.officeuser.entity.Order;
import com.topboya.officeuser.utils.HttpClientUtils;
import com.topboya.officeuser.utils.UtilTools;
import com.topboya.officeuser.utils.WeixinPayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @className WxPayService
 * @Author xiaxin
 * @Date 2020/12/21 13:18
 * @Version 1.0
 **/
@Service
public class WxPayService {
    @Autowired
    private WeixinPayProperties weixinPayProperties;

    public Map createNative(String orderNo, String remoteAddr) throws Exception {
        Order order = new Order();
        order.setId(UUID.randomUUID().toString());
        order.setOrderNumber(orderNo);
        order.setIntroduce("这是一部手机");
        order.setDetail("小米品牌");
        order.setPrice("1999");

        HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");

        Map<String,String> params = new HashMap<>();
        params.put("appid",weixinPayProperties.getAppId());
        params.put("mch_id",weixinPayProperties.getPartner());
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body",order.getIntroduce());
        params.put("out_trade_no",orderNo);
        String totalFee = order.getPrice() + "";
        params.put("total_fee", totalFee);

        params.put("spbill_create_ip",remoteAddr);
        params.put("notify_url",weixinPayProperties.getNotifyUrl());
        params.put("trade_type","NATIVE");

        String xmlParams = WXPayUtil.generateSignedXml(params,weixinPayProperties.getPartnerKey());
        System.out.println(xmlParams);
        client.setXmlParam(xmlParams);
        client.setHttps(true);
        client.post();
        String resultXml = client.getContent();
       // System.out.println("相应结果:"+resultXml);

        Map<String,String> resultMap = WXPayUtil.xmlToMap(resultXml);
        System.out.println(resultMap);
        String codeUrl = resultMap.get("code_url");


        Map<String,Object> map = new HashMap<>();
        map.put("result_code",resultMap.get("result_code"));
        map.put("code_url",resultMap.get("code_url"));
        map.put("order_id",order.getId());
        map.put("total_fee",order.getPrice());
        map.put("out_trade_no",orderNo);



        return map;
    }
}
